//本进程处理主页相关内容

const applyMysql = require('./tools/applyMysql');

const os = require('os');
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const koaStatic = require('koa-static');
const indexRouter = require('./http/index');
const Cors = require('koa-cors');
let Router = require('koa-router');
const {resolve} = require('path')
const fs = require('fs');
const ini = require('ini');
const Log =require('./Logger/Logger');
const home = require('./Manager/Home').home;
const avenirsql = require('avenirsql');
async function init() {
    // let mysqlInstance = new applyMysql();
    let log = new Log('Home','./log');
    global.log = log;   //这样拿起来方便
    let file = await giveFileName();
    let ini = await readIni(file);
    ini.Mysql.ip = os.platform() == 'linux' ? '127.0.0.1': ini.Mysql.ip;
    avenirsql.init({
        ip:ini.Mysql.ip,
        user:ini.Mysql.name,
        password:ini.Mysql.password,
        port:ini.Mysql.port,
        database:ini.Mysql.database,
    })

    global.instance = {
        dbHandler : avenirsql,

        home:home,
        ini:ini,
        fileName:file,
    };

    


}
async function main() {
    await init();

    start();

}


async function giveFileName() {
    let type = os.platform();
    log.debug('type = ',type);
    let fileName;
    if(type == "win32")
    {
        fileName = "F:/my-web/BackEnd/run.ini";

    }
    else
    {
        fileName = "./run.ini"

    }
    return fileName;
}


async function readIni(fileName) {
    let file = fs.readFileSync(fileName);
    var Info = ini.parse(file.toString());
    return Info;
}

function start() {
    const app = new Koa();
    app.use(koaStatic('/home/only/my-web/FrontEnd/dist'));
    app.use(bodyParser());
    app.use(Cors());
    var router = new Router();
    router.use('',indexRouter);
    app.use(router.routes());
    app.use(router.allowedMethods());

    let port = instance.ini.main.port;
    app.listen(port, () => {
        log.debug("http服务器已启动，127.0.0.1:",port);
    })
}


main();